package com.yulan.bankback.service.admin.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yulan.bankback.entity.model.admin.BlackUserPromote;
import com.yulan.bankback.entity.dto.bank.PieChartDto;
import com.yulan.bankback.entity.model.admin.BlackUserRegion;
import com.yulan.bankback.entity.model.admin.IllegalTrading;
import com.yulan.bankback.entity.model.admin.KindUser;
import com.yulan.bankback.entity.model.bank.BankUser;
import com.yulan.bankback.entity.vo.BlackUserVo;
import com.yulan.bankback.mapper.admin.BlackUserRegionMapper;
import com.yulan.bankback.mapper.admin.IllegalTradingMapper;
import com.yulan.bankback.mapper.admin.KindUserMapper;
import com.yulan.bankback.mapper.bank.BankUserMapper;
import com.yulan.bankback.service.admin.BlackUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BlackUserServiceImpl implements BlackUserService {

    @Resource
    private KindUserMapper kindUserMapper;

    @Resource
    private BlackUserRegionMapper blackUserRegionMapper;

    @Resource
    private BankUserMapper bankUserMapper;

    @Resource
    private IllegalTradingMapper illegalTradingMapper;

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");

    private static final SimpleDateFormat formatter3 = new SimpleDateFormat("MM-dd");


    @Override
    public BlackUserVo getBlackUserVo(String interval) {
        BlackUserVo vo = new BlackUserVo();
        List<BlackUserPromote> promoteDtos = kindUserMapper.getIntervalPromote(interval);
        List<String> date = promoteDtos.stream().map(item ->
                formatter3.format(item.getTime()))
                .collect(Collectors.toList());
        while(date.size() > 10){
            date = this.changeListSize(date, 4);
        }

        List<Integer> data = promoteDtos.stream().map(
                BlackUserPromote::getCount)
                .collect(Collectors.toList());

        while(data.size() > 10){
            data = this.changeListSize(data, 4);
        }

        vo.setBlackUserUpDate(date);
        vo.setBlackUserUpData(data);

        List<BlackUserRegion> blackUserRegions = blackUserRegionMapper.selectList(
                new QueryWrapper<BlackUserRegion>().orderByDesc("count").last("limit 6"));
        List<PieChartDto<Integer>> blackUserRegionGroup = new ArrayList<>();
        blackUserRegions.forEach(item ->
                blackUserRegionGroup.add(new
                        PieChartDto<Integer>(item.getCount(), item.getRegionName())));
        vo.setBlackUserRegionGroup(blackUserRegionGroup);
        return vo;
    }

    @Override
    public List<KindUser> getBlackUser() {
        List<KindUser> kindUsers = kindUserMapper.selectList(
                new QueryWrapper<KindUser>()
                        .eq("black_or_white", "black")
                        .last("limit 500"));
        kindUsers.forEach(item -> item.setViewTime(formatter.format(item.getCreateTime())));
        return kindUsers;
    }

    @Override
    public List<KindUser> getBlackUserByConditions(String start, String end,
                                                   String type, String username, String uid) {
        QueryWrapper<KindUser> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(start)){
            queryWrapper.gt("create_time", DateUtil.parseDate(start));
        }
        if(StringUtils.isNotBlank(end)){
            queryWrapper.lt("create_time", DateUtil.parseDate(end));
        }
        if(StringUtils.isNotBlank(type)) queryWrapper.eq("type", type);
        if(StringUtils.isNotBlank(username)) queryWrapper.eq("username", username);
        if(StringUtils.isNotBlank(uid)) queryWrapper.eq("uid", uid);
        queryWrapper.eq("black_or_white", "black");
        List<KindUser> res = kindUserMapper.selectList(queryWrapper);
        res.forEach(item -> item.setViewTime(formatter.format(item.getCreateTime())));
        return res;
    }

    @Override
    public List<KindUser> getWhiteUser() {
        List<KindUser> kindUsers = kindUserMapper.selectList(
                new QueryWrapper<KindUser>()
                        .eq("black_or_white", "white")
                        .last("limit 500"));
        kindUsers.forEach(item -> item.setViewTime(formatter.format(item.getCreateTime())));
        return kindUsers;

    }

    @Override
    public List<KindUser> getWhiteUserByConditions(String start, String end,
                                                   String type, String username, String uid) {
        QueryWrapper<KindUser> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(start)) {
            queryWrapper.gt("create_time", DateUtil.parseDate(start));
        }
        if(StringUtils.isNotBlank(end)) {{
            queryWrapper.lt("create_time", DateUtil.parseDate(end));
        }}
        if(StringUtils.isNotBlank(type)) queryWrapper.eq("type", type);
        if(StringUtils.isNotBlank(username)) queryWrapper.eq("username", username);
        if(StringUtils.isNotBlank(uid)) queryWrapper.eq("uid", uid);
        queryWrapper.eq("black_or_white", "white");
        List<KindUser> res = kindUserMapper.selectList(queryWrapper);
        res.forEach(item -> item.setViewTime(formatter.format(item.getCreateTime())));
        return res;
    }

    @Override
    public String addWhiteUser(String uid, String username, String type) {
        BankUser user = null;

        if(StringUtils.isNotBlank(uid)) {
            user = bankUserMapper.selectById(uid);
            if(user == null) return "没有该用户";
        }

        if(StringUtils.isNotBlank(username)){
            int count = bankUserMapper.selectCount(
                    new QueryWrapper<BankUser>()
                            .eq("user_name", username));
            if(count == 1 && user == null){
                user = bankUserMapper.selectOne(
                        new QueryWrapper<BankUser>().eq("user_name", username));
            }
        }

        if(user == null)
            return "没有该用户";

        KindUser kindUser = null;

        //查询是否已经存在
        kindUser = kindUserMapper.selectOne(new QueryWrapper<KindUser>()
                .eq("uid", user.getId())
                .eq("black_or_white", "white"));
        if(kindUser != null)
            return "该用户已经存在于白名单当中";

        kindUser = new KindUser(user.getId(), user.getUserName(), new Date(), type, "white");
        kindUserMapper.insert(kindUser);
        return "success";
    }

    @Override
    public String addBlackUser(String uid, String username, String type) {
        BankUser user = null;

        if(StringUtils.isNotBlank(uid)) {
            user = bankUserMapper.selectById(uid);
            if(user == null) return "没有该用户";
        }

        if(StringUtils.isNotBlank(username)){
            int count = bankUserMapper.selectCount(
                    new QueryWrapper<BankUser>()
                            .eq("user_name", username));
            if(count == 1 && user == null){
                user = bankUserMapper.selectOne(
                        new QueryWrapper<BankUser>().eq("user_name", username));
            }
        }

        if(user == null)
            return "没有该用户";

        KindUser kindUser = null;

        //查询是否已经存在
        kindUser = kindUserMapper.selectOne(new QueryWrapper<KindUser>()
                .eq("uid", user.getId())
                .eq("black_or_white", "black"));
        if(kindUser != null)
            return "该用户已经存在于黑名单当中";


        kindUser = new KindUser(user.getId(), user.getUserName(), new Date(), type, "black");
        kindUserMapper.insert(kindUser);

        IllegalTrading illegalTrading = illegalTradingMapper.selectById(kindUser.getUid());
        if(illegalTrading != null){
            UpdateWrapper<IllegalTrading> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("uid", kindUser.getUid()).set("isBlack", 1);
        }


        return "success";
    }

    @Override
    public String removeBlackUser(String uid, String username) {
        KindUser kindUser = null;
        if(StringUtils.isNotBlank(uid))
            kindUser = kindUserMapper.selectOne(
                new QueryWrapper<KindUser>().eq("uid", uid)
                        .eq("black_or_white", "black"));
        if(kindUser == null && StringUtils.isNotBlank(username))
            kindUser = kindUserMapper.selectOne(
                new QueryWrapper<KindUser>().eq("username", username)
                        .eq("black_or_white", "black"));
        if(kindUser == null)
            return "不存在该用户";

        int count = kindUserMapper.deleteById(kindUser.getUid());

        IllegalTrading illegalTrading = illegalTradingMapper.selectById(kindUser.getUid());
        if(illegalTrading != null){
            UpdateWrapper<IllegalTrading> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("uid", kindUser.getUid()).set("isBlack", 0);
        }

        return count == 1 ? "success" : "移除失败";
    }

    @Override
    public String removeWhiteUser(String uid, String username) {
        KindUser kindUser = null;
        if(StringUtils.isNotBlank(uid))
            kindUser = kindUserMapper.selectOne(
                    new QueryWrapper<KindUser>().eq("uid", uid)
                            .eq("black_or_white", "white"));
        if(kindUser == null && StringUtils.isNotBlank(username))
            kindUser = kindUserMapper.selectOne(
                    new QueryWrapper<KindUser>().eq("username", username)
                            .eq("black_or_white", "white"));
        if(kindUser == null)
            return "不存在该用户";

        int count = kindUserMapper.deleteById(kindUser.getUid());

        return count == 1 ? "success" : "移除失败";
    }

    private <T> List<T> changeListSize(List<T> list, int mod){
        T first = list.get(0);
        T last = list.get(list.size() - 1);

        List<T> res = new ArrayList<>();
        res.add(first);
        for(int i = 1; i < list.size() - 1; i++){
            if(i % mod != 0)
                res.add(list.get(i));
        }
        res.add(last);
        return res;
    }

}
